<?php

namespace App\Services\ApplyGoldProductReselling;

use Carbon\Carbon;
use App\Models\User;
use App\Models\GoldRecord;
use App\Models\GoldProduct;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class ApplyGoldProductReselling
{
	/**
	 * @var User
	 */
	protected $user;

	/**
	 * @var GoldRecord
	 */
	protected $record = null;

	public function __construct(User $user, $pendingCacheId)
	{
		$this->user = $user;

		if ($pendingCacheId instanceof GoldRecord) {
			$this->record = $pendingCacheId;
		} else {
			$recordId = (int)Redis::hGet($pendingCacheId, 'gold_record_id');
			$record = $recordId > 0 ? GoldRecord::find($recordId) : null;
			$this->record = $record ?? null;
		}
	}

	protected function deductResellingBeans()
	{
        $beans = $this->record->pay_gold_beans;
        $data = ['gold_record_id' => $this->record->id];
		account_beans($this->user)->minusResellFeeBeans($beans, $data);
	}

	protected function updateGoldRecord()
	{
		$goldRecord = $this->record->fresh();
        $goldProduct = $goldRecord->goldProduct->fresh();

		$goldRecord->update(['to_resell_applied_at' => Carbon::now()]);
        $goldProduct->update(['started_at' => $goldRecord->nextResellAt()]);

		$this->user->markRecordCacheAsResell($goldRecord);
	}

	protected function resell()
	{
		DB::transaction(function () {
			if (!$this->user->is_mock) {
                $this->deductResellingBeans();
            }
            $this->updateGoldRecord();
        });

		return $this->record;
	}

	public function apply()
	{
		if (! $this->record) return null;

		return $this->resell();
	}
}
